package jersy.server.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;

import pojo.User;
@Path("/users")
public class Server {
	private Map<Integer, User> users = new HashMap<Integer,User>();
	private Integer index = 0;
	
	public Server() {
		if(index == 0)
		{
			users.put(index, new User("1","anegrs1",11,"2443304401"));
			index++;
			users.put(index, new User("2","anegrs2",12,"2443304402"));
			index++;
			users.put(index, new User("3","anegrs3",13,"2443304403"));
			index++;
		}
	}
	
	@GET
	@Path("{userid}")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public User getUser(@PathParam("userid") Integer id){
		if(users.containsKey(id)){
			return users.get(id);
		}
		else{
			return null;
		}
	}
	
	@GET
	@Path("list")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public List<User> listUsers(){
		List<User> list = new ArrayList<User>();
		for(int i=0;i<index;i++){
			list.add(users.get(i));
		}
		return  list;
	}
	
	@POST
	@Path("add")
	@Produces(MediaType.APPLICATION_XML)  
	public User addUsers(@FormParam("id") String id,@FormParam("name") String name, @FormParam("age") Integer age, @FormParam("email") String email){
		User user = new User(id,name,age, email);
		System.out.println(user);
		users.put(index, user);
		index++;
		for(int i=0;i<index;i++){
			System.out.println(users.get(i));
		}
		return user;
	}
	
		@DELETE
	    @Path("delete/{userid}")
	     @Produces("text/plain")
	     public String removeStudent(@PathParam("userid") int id) {
	         User removed = users.remove(id);
	         System.out.println(removed);
	         if(removed==null) return "failed!";
	         else   return "true";
	    } 
}
